import { Category } from "@/models/Category";
import { Manager } from "@/models/Manager";
import { Product } from "@/models/Product";
import { Store } from "@/models/Store";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";

const productRoute = new Hono();

const querySchema = z.object({
  page: z.coerce.number().default(1),
  pageSize: z.coerce.number().default(10),
});

productRoute.get("/", async (c) => {
  // 获取产品详情
  let id = c.req.query("id");

  if (!id) {
    throw new HTTPException(400, { message: "id is required" });
  }

  let product = await Product.findOneBy({ id: Number(id) });

  if (!product) {
    throw new HTTPException(404, { message: "产品不存在" });
  }

  return c.json({ message: "success", code: 200, data: product });
});

productRoute.get("/list", async (c) => {
  let query = c.req.query();
  let result = querySchema.safeParse(query);

  if (!result.success) {
    let message =
      result.error.issues[0].path + " " + result.error.issues[0].message;

    throw new HTTPException(400, { message });
  }

  let [list, count] = await Product.findAndCount({
    skip: (Number(result.data.page) - 1) * Number(result.data.pageSize),
    take: Number(result.data.pageSize),
  });

  return c.json({ message: "success", code: 200, data: { list, count } });
});

const addSchema = z.object({
  name: z.string(),
  mainImage: z.string(),
  images: z.string(),
  description: z.string(),
  price: z.coerce.number(),
  stock: z.coerce.number(),
  discountPrice: z.coerce.number(),
  sales: z.coerce.number(),
  categoryId: z.coerce.number().nullable(),
  storeId: z.coerce.number(),
});

const updateSchema = z.object({
  id: z.coerce.number(),
  name: z.string(),
  mainImage: z.string(),
  images: z.string(),
  description: z.string(),
  price: z.coerce.number(),
  stock: z.coerce.number(),
  discountPrice: z.coerce.number(),
  sales: z.coerce.number(),
  categoryId: z.coerce.number(),
  storeId: z.coerce.number(),
});

productRoute.post("/add", async (c) => {
  // 获取storeId
  let payload = await c.get("jwtPayload");
  let id = payload?.id;
  let manager = await Manager.findOne({
    where: { id },
    relations: { store: true },
  });

  if (!manager) {
    throw new HTTPException(404, { message: "管理员不存在" });
  }

  let store = manager.store;
  if (!store) {
    throw new HTTPException(404, { message: "门店不存在" });
  }

  let body = await c.req.parseBody();
  let result = addSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let product = new Product();

  product.name = result.data.name;
  product.mainImage = result.data.mainImage;
  product.images = result.data.images;
  product.description = result.data.description;
  product.price = result.data.price;
  product.stock = result.data.stock;
  product.discountPrice = result.data.discountPrice;
  product.sales = result.data.sales;
  product.store = store;

  if (result.data.categoryId) {
    let category = await Category.findOneBy({ id: result.data.categoryId });

    if (category) {
      product.category = category;
    }
  }

  await product.save();

  return c.json({ message: "hello", code: 200, data: product });
});

productRoute.post("/edit", async (c) => {
  let body = await c.req.parseBody();
  let result = updateSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let product = await Product.findOneBy({ id: result.data.id });

  if (!product) {
    throw new HTTPException(404, { message: "产品不存在" });
  }

  let store = await Store.findOneBy({ id: result.data.storeId });

  product.name = result.data.name;
  product.mainImage = result.data.mainImage;
  product.images = result.data.images;
  product.description = result.data.description;
  product.price = result.data.price;
  product.stock = result.data.stock;
  product.discountPrice = result.data.discountPrice;
  product.sales = result.data.sales;
  product.store = store;

  await product.save();

  return c.json({ message: "hello", code: 200, data: product });
});

export default productRoute;
